//
//  KeyboardEmoticonViewController.swift
//  Emoji
//
//  Created by 钟清 on 17/4/10.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit

class KeyboardEmoticonViewController: UIViewController {
    /* 保存所有组数据 */
    var package: [KeyboardEmoticonPackage] = KeyboardEmoticonPackage.loadEmoticonPackages()
    /* 回调的闭包属性 */
    var emoticonCallBack:(emoticon: KeyboardEmoticons) -> ()
    /* 控制器的init方法 */
    init(callBack: (emoticon: KeyboardEmoticons) -> ()) {
        self.emoticonCallBack = callBack
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        /*  1,添加子控件 */
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        /* 2,布局子控件 */
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        let dict = ["collectionView" : collectionView, "toolbar" : toolbar]
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-[toolbar(49)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
        view.addConstraints(cons)
    }
    
    // MARK: - Lazy
    private lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: KeyboardEmoticonCollectionViewLayout())
        clv.backgroundColor = UIColor.greenColor()
        clv.dataSource = self
        clv.delegate = self
        clv.registerClass(KeyboardEmoticonCell.self, forCellWithReuseIdentifier: "keyboardCell")
        return clv
    }()
    private lazy var toolbar: UIToolbar = {
        let tb = UIToolbar()
        tb.tintColor = UIColor.lightGrayColor()
        var items = [UIBarButtonItem]()
        var index = 0
        for title in ["最近", "默认", "Emoji", "浪小花"] {
            let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(KeyboardEmoticonViewController.itemClick(_:)))
            item.tag = index
            index += 1
            items.append(item)
            let flexibleItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(flexibleItem)
        }
        items.removeLast()
        tb.items = items
        return tb
    }()
    
    // MARK: - 内部控制方法
    /* 滚动到对应的indexPath */
    @objc private func itemClick(item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
}

// MARK: - DataSource
extension KeyboardEmoticonViewController: UICollectionViewDataSource {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return package.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return package[section].emoticons?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        /* 创建cell */
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("keyboardCell", forIndexPath: indexPath) as! KeyboardEmoticonCell
        /* 赋值cell */
        cell.emoticon = package[indexPath.section].emoticons![indexPath.item]
        /* 返回cell */
        return cell
    }
}
// MARK: - Delegate
extension KeyboardEmoticonViewController: UICollectionViewDelegate {
    /* 监听表情点击 */
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = package[indexPath.section].emoticons![indexPath.item]
        /* 选中一次自增1 */
        emoticon.count += 1
        /* 添加选中表情 */
        if !emoticon.isRemoveButton {
            package[0].addFavouriteEmoticon(emoticon)
        }
        /* 将表情传递到出去 */
        emoticonCallBack(emoticon: emoticon)
        
    }
}

class KeyboardEmoticonCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        /* cell尺寸设置 */
        let width = UIScreen.mainScreen().bounds.width / 7
        let height = (collectionView?.bounds.height)! / 3
        itemSize = CGSize(width: width, height: height)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        /* collectionView设置 */
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        
    }
}
